var express = require('express');
var router = express.Router();
var path = require('path');
var MongoClient = require('mongodb').MongoClient;
var DB_CONN_STR="mongodb://localhost:27017/product";

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

//登录
router.post('/login',function(req,res,next){
  var phone=req.body.phone;
  var password=req.body.password;

  MongoClient.connect(DB_CONN_STR,function(err,db){
    if(err){
      console.log(err);
      return;
    }else{
      var conn = db.collection('user');
      var data={phone:phone,password:password};
      conn.find(data).toArray(function(err,results){
        if(results.length>0){
          req.session.phone = results[0].phone;
          res.redirect('/');
        }else{
          res.send('请输入正确的手机号和密码！');
        }
      })
    }
  })
})

router.post('/register',function(req,res,next){
  var phone=req.body.phone;
  var password=req.body.password;

  MongoClient.connect(DB_CONN_STR,function(err,db){
    if(err){
      console.log(err);
      return;
    }
    else{
      var conn = db.collection('user');
      var flag={phone:phone};
      var data={phone:phone,password:password};
      conn.find(flag).toArray(function(err,results){
        if(results.length>0){
          res.send('用户已经被注册!<a href="/register">返回</a>');
        }
        else{
          conn.insert(data,function(err,results){
            res.redirect('/login');
            db.close();
          })
        }
      });
    }
  })
})

module.exports = router;
